/**
 * 任务页面事件处理器
 * 负责处理任务页面相关的所有事件和逻辑
 */
class TasksHandler {
  constructor(appState, apiService, uiUtils) {
    this.appState = appState;
    this.apiService = apiService;
    this.uiUtils = uiUtils;
    this.currentWorkPath = null;
    this.claudeConnected = false;
    this.checkingConnection = false;
    this.streamCleanupFunctions = []; // 存储流式监听的清理函数
    this.typingQueue = []; // 待打字的字符队列
    this.isTyping = false; // 是否正在打字
    this.typingSpeed = 30; // 打字速度（毫秒/字符）
  }

  /**
   * 初始化任务页面
   */
  async init() {
    console.log("[TasksHandler] 初始化任务页面");

    // 初始化连接状态
    this.updateConnectionStatus("disconnected", "未连接", "请先选择工作路径");

    // 设置流式事件监听
    this.setupStreamListeners();

    // 延迟执行，确保 DOM 完全加载
    setTimeout(() => {
      this.bindEvents();
    }, 100);
  }

  /**
   * 绑定任务页面事件
   */
  bindEvents() {
    console.log("[TasksHandler] 设置任务页面按钮事件");

    // 绑定选择文件夹按钮事件
    this.bindButton("select-path-btn", this.handleSelectPath.bind(this));

    // 绑定打开文件位置按钮事件
    this.bindButton("open-location-btn", this.handleOpenLocation.bind(this));

    // 绑定路径输入框点击事件
    const pathInput = document.getElementById("work-path-input");
    if (pathInput) {
      pathInput.addEventListener("click", () => {
        this.handleSelectPath();
      });
    }

    // 绑定任务执行按钮事件
    this.bindButton("execute-task-btn", this.handleExecuteTask.bind(this));

    // 绑定清空任务按钮事件
    this.bindButton("clear-task-btn", this.handleClearTask.bind(this));

    // 绑定复制结果按钮事件
    this.bindButton("copy-result-btn", this.handleCopyResult.bind(this));

    // 绑定清空结果按钮事件
    this.bindButton("clear-result-btn", this.handleClearResult.bind(this));

    // 绑定命令行模式按钮事件
    this.bindButton("code-mode-btn", this.handleCodeMode.bind(this));

    // 绑定对话历史按钮事件
    this.bindButton("history-btn", this.handleShowHistory.bind(this));

    // 绑定关闭侧边栏按钮事件
    this.bindButton("close-history-btn", this.handleCloseHistory.bind(this));

    // 绑定侧边栏遮罩点击事件
    const sidebarOverlay = document.getElementById("sidebar-overlay");
    if (sidebarOverlay) {
      sidebarOverlay.addEventListener("click", () => {
        this.handleCloseHistory();
      });
    }

    // 绑定任务输入框快捷键
    const taskInput = document.getElementById("task-input");
    if (taskInput) {
      taskInput.addEventListener("keydown", (e) => {
        this.handleTaskInputKeydown(e);
      });
    }
  }

  /**
   * 处理任务输入框键盘事件
   * @param {KeyboardEvent} e - 键盘事件
   */
  handleTaskInputKeydown(e) {
    // Enter 键（不按 Shift）→ 发送任务
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault(); // 阻止默认换行
      this.handleExecuteTask();
    }
    // Shift + Enter → 换行（默认行为，不需要特殊处理）
  }

  /**
   * 绑定按钮事件
   * @param {string} buttonId - 按钮 ID
   * @param {Function} handler - 事件处理器
   */
  bindButton(buttonId, handler) {
    const button = document.getElementById(buttonId);
    if (button) {
      button.addEventListener("click", handler);
    }
  }

  /**
   * 处理选择文件夹
   */
  async handleSelectPath() {
    console.log("[TasksHandler] 处理选择文件夹");

    try {
      // 检查 electronAPI 是否可用
      if (!window.electronAPI || !window.electronAPI.selectFolder) {
        console.error("[TasksHandler] electronAPI 不可用");
        this.uiUtils.showMessage("文件夹选择功能不可用", "error");
        return;
      }

      // 使用 IPC 调用选择文件夹
      const result = await window.electronAPI.selectFolder();
      console.log("[TasksHandler] 选择文件夹结果:", result);

      if (result.success && result.path) {
        const selectedPath = result.path;
        console.log("[TasksHandler] 选择的路径:", selectedPath);

        // 更新路径输入框
        const pathInput = document.getElementById("work-path-input");
        if (pathInput) {
          pathInput.value = selectedPath;
        }

        // 启用打开文件位置按钮
        const openLocationBtn = document.getElementById("open-location-btn");
        if (openLocationBtn) {
          openLocationBtn.disabled = false;
        }

        // 保存当前工作路径
        this.currentWorkPath = selectedPath;

        this.uiUtils.showMessage("工作路径设置成功", "success");

        // 检测 Claude 连接状态
        await this.checkClaudeConnection();
      } else if (result.canceled) {
        console.log("[TasksHandler] 用户取消了选择");
      } else {
        console.error("[TasksHandler] 选择文件夹失败:", result.error);
        this.uiUtils.showMessage(
          `选择文件夹失败: ${result.error || "未知错误"}`,
          "error"
        );
      }
    } catch (error) {
      console.error("[TasksHandler] 选择文件夹异常:", error);
      this.uiUtils.showMessage(`选择文件夹异常: ${error.message}`, "error");
    }
  }

  /**
   * 处理打开文件位置
   */
  async handleOpenLocation() {
    console.log("[TasksHandler] 处理打开文件位置");

    if (!this.currentWorkPath) {
      this.uiUtils.showMessage("请先选择工作路径", "error");
      return;
    }

    try {
      // 检查 electronAPI 是否可用
      if (!window.electronAPI || !window.electronAPI.openFolderLocation) {
        console.error("[TasksHandler] electronAPI 不可用");
        this.uiUtils.showMessage("打开文件夹功能不可用", "error");
        return;
      }

      // 使用 IPC 调用打开文件夹
      const result = await window.electronAPI.openFolderLocation(
        this.currentWorkPath
      );
      console.log("[TasksHandler] 打开文件位置结果:", result);

      if (result.success) {
        console.log("[TasksHandler] 打开文件位置成功:", this.currentWorkPath);
        // 不显示成功提示，因为已经打开了文件夹
      } else {
        console.error("[TasksHandler] 打开文件位置失败:", result.error);
        this.uiUtils.showMessage(
          `打开文件夹失败: ${result.error || "未知错误"}`,
          "error"
        );
      }
    } catch (error) {
      console.error("[TasksHandler] 打开文件位置异常:", error);
      this.uiUtils.showMessage(`打开文件夹异常: ${error.message}`, "error");
    }
  }

  /**
   * 处理执行任务
   */
  async handleExecuteTask() {
    console.log("[TasksHandler] 处理执行任务");

    const taskInput = document.getElementById("task-input");
    const executeBtn = document.getElementById("execute-task-btn");
    const workPathInput = document.getElementById("work-path-input");

    if (!taskInput || !executeBtn) return;

    const task = taskInput.value.trim();
    const workPath = workPathInput ? workPathInput.value.trim() : "";

    // 验证输入 - 必须先选择工作路径
    if (!workPath || !this.currentWorkPath) {
      this.uiUtils.showMessage("请先选择工作路径后再执行任务", "error");

      // 高亮显示路径选择区域
      const pathInput = document.getElementById("work-path-input");
      if (pathInput) {
        pathInput.style.border = "2px solid #ef4444";
        setTimeout(() => {
          pathInput.style.border = "";
        }, 2000);
      }
      return;
    }

    // 验证任务描述
    if (!task) {
      this.uiUtils.showMessage("请输入任务描述", "error");
      taskInput.focus();
      return;
    }

    try {
      // 清空之前的打字队列
      this.clearTypingQueue();

      // 更新按钮状态
      executeBtn.disabled = true;
      executeBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 执行中...';

      // 更新状态显示
      this.updateTaskStatus("processing", "正在执行任务...");
      this.showResultActions(false);

      // 显示执行日志
      this.displayExecutionLog(task, workPath);

      // 执行任务
      const result = await this.performTask(task, workPath);

      if (result.success) {
        this.displayTaskResult(result.content);
        this.updateTaskStatus("success", "任务执行成功");
        this.showResultActions(true);

        // 保存到工作路径历史
        await this.saveTaskToHistory(task, result, "success");

        this.uiUtils.showMessage("任务执行成功！", "success");
      } else {
        this.displayTaskError(result.error);
        this.updateTaskStatus("error", "任务执行失败");
        this.showResultActions(true);

        // 保存失败记录到历史
        await this.saveTaskToHistory(task, result, "error");

        this.uiUtils.showMessage(`任务执行失败: ${result.error}`, "error");
      }
    } catch (error) {
      console.error("[TasksHandler] 任务执行异常:", error);
      this.displayTaskError(error.message);
      this.updateTaskStatus("error", "任务执行异常");
      this.showResultActions(true);

      this.uiUtils.showMessage(`任务执行异常: ${error.message}`, "error");
    } finally {
      // 恢复按钮状态
      executeBtn.disabled = false;
      executeBtn.innerHTML = '<i class="fas fa-paper-plane"></i> 发送任务';
    }
  }

  /**
   * 设置流式事件监听
   */
  setupStreamListeners() {
    if (!window.electronAPI) {
      console.warn("[TasksHandler] electronAPI 不可用，跳过流式监听设置");
      return;
    }

    console.log("[TasksHandler] 设置流式事件监听");

    // 监听流式数据
    if (window.electronAPI.onStreamData) {
      const cleanupData = window.electronAPI.onStreamData((data) => {
        this.handleStreamData(data);
      });
      this.streamCleanupFunctions.push(cleanupData);
    }

    // 监听流式完成
    if (window.electronAPI.onStreamComplete) {
      const cleanupComplete = window.electronAPI.onStreamComplete((data) => {
        this.handleStreamComplete(data);
      });
      this.streamCleanupFunctions.push(cleanupComplete);
    }

    // 监听流式错误
    if (window.electronAPI.onStreamError) {
      const cleanupError = window.electronAPI.onStreamError((data) => {
        this.handleStreamError(data);
      });
      this.streamCleanupFunctions.push(cleanupError);
    }

    console.log("[TasksHandler] 流式事件监听已设置");
  }

  /**
   * 处理流式数据
   */
  handleStreamData(data) {
    console.log("[TasksHandler] 收到流式数据:", data.type);

    if (data.type === "text-chunk") {
      // 实时更新输出内容
      this.appendStreamOutput(data.text);
    } else if (data.type === "assistant") {
      // 助手消息开始
      console.log("[TasksHandler] 助手开始响应");
    } else if (data.type === "final-result") {
      // 最终结果
      console.log("[TasksHandler] 收到最终结果");
    }
  }

  /**
   * 处理流式完成
   */
  handleStreamComplete(data) {
    console.log("[TasksHandler] 流式输出完成:", data);
    // 完成信号已经在 performTask 的 await 中处理
  }

  /**
   * 处理流式错误
   */
  handleStreamError(data) {
    console.log("[TasksHandler] 流式输出错误:", data);
    this.displayTaskError(data.error);
  }

  /**
   * 追加流式输出内容（打字机效果）
   */
  appendStreamOutput(text) {
    const outputContainer = document.getElementById("task-output");
    if (!outputContainer) return;

    // 查找或创建流式输出容器
    let streamContainer = outputContainer.querySelector(
      ".stream-output-content"
    );

    if (!streamContainer) {
      outputContainer.innerHTML = `
                <div class="stream-output-content"></div>
            `;
      streamContainer = outputContainer.querySelector(".stream-output-content");
    }

    // 将文本拆分为字符数组，加入打字队列
    const characters = Array.from(text); // 使用 Array.from 正确处理 Unicode 字符
    this.typingQueue.push(...characters);

    // 如果没有在打字，开始打字
    if (!this.isTyping) {
      this.startTyping();
    }
  }

  /**
   * 开始打字效果
   */
  startTyping() {
    if (this.isTyping || this.typingQueue.length === 0) return;

    this.isTyping = true;
    const outputContainer = document.getElementById("task-output");
    const streamContainer = outputContainer?.querySelector(
      ".stream-output-content"
    );

    if (!streamContainer) {
      this.isTyping = false;
      return;
    }

    const typeNextChar = () => {
      if (this.typingQueue.length === 0) {
        // 打字完成，移除光标效果
        this.isTyping = false;
        if (streamContainer) {
          streamContainer.classList.add("typing-complete");
        }
        console.log("[TasksHandler] 打字效果完成");
        return;
      }

      // 取出下一个字符
      const char = this.typingQueue.shift();

      // 添加字符到容器
      const textNode = document.createTextNode(char);
      streamContainer.appendChild(textNode);

      // 自动滚动到底部
      if (outputContainer) {
        outputContainer.scrollTop = outputContainer.scrollHeight;
      }

      // 调整打字速度：中文慢一点，英文和符号快一点
      let speed = this.typingSpeed;
      if (/[\u4e00-\u9fa5]/.test(char)) {
        // 中文字符
        speed = 50;
      } else if (/[a-zA-Z0-9]/.test(char)) {
        // 英文和数字
        speed = 30;
      } else if (char === "\n") {
        // 换行符，稍微快一点
        speed = 10;
      } else {
        // 标点符号等
        speed = 20;
      }

      // 继续打下一个字符
      setTimeout(typeNextChar, speed);
    };

    // 开始打字
    typeNextChar();
  }

  /**
   * 清空打字队列
   */
  clearTypingQueue() {
    this.typingQueue = [];
    this.isTyping = false;
  }

  /**
   * 启动 Claude 会话
   */
  async startSession() {
    try {
      console.log("[TasksHandler] 启动 Claude 会话");

      if (!window.electronAPI || !window.electronAPI.startClaudeSession) {
        throw new Error("会话管理 API 不可用");
      }

      // 获取存储的 API Key
      const apiKeyResult = await window.electronAPI.loadApiKey();
      if (!apiKeyResult.success || !apiKeyResult.apiKey) {
        throw new Error("未配置 API Key");
      }

      const result = await window.electronAPI.startClaudeSession({
        apiKey: apiKeyResult.apiKey,
        workPath: this.currentWorkPath,
      });

      console.log("[TasksHandler] Claude 会话启动结果:", result);

      if (!result.success) {
        console.error("[TasksHandler] 会话启动失败:", result.error);
        this.uiUtils.showMessage(`会话启动失败: ${result.error}`, "error");
      }
    } catch (error) {
      console.error("[TasksHandler] 启动会话异常:", error);
      this.uiUtils.showMessage(`会话启动异常: ${error.message}`, "error");
    }
  }

  /**
   * 执行任务
   * @param {string} task - 任务描述
   * @param {string} workPath - 工作路径
   * @returns {Object} 执行结果
   */
  async performTask(task, workPath) {
    console.log("[TasksHandler] 执行任务:", { task, workPath });

    try {
      // 检查 API 是否可用
      if (!window.electronAPI || !window.electronAPI.executeWithSession) {
        throw new Error("Claude 执行 API 不可用");
      }

      // 使用会话执行任务
      const result = await window.electronAPI.executeWithSession({
        task: task,
      });

      console.log("[TasksHandler] Claude 执行结果:", result);

      if (result.success) {
        // 格式化成功结果
        let content = this.formatClaudeOutput(
          result.output || result.result,
          task,
          workPath
        );

        // 如果任务超时但有输出，添加提示
        if (result.timedOut) {
          content =
            `⚠️ **注意**: 任务执行超时（60秒），但已获取部分输出\n\n` + content;
        }

        return {
          success: true,
          content: content,
          timedOut: result.timedOut,
        };
      } else {
        // 执行失败
        return {
          success: false,
          error: result.error || result.message || "任务执行失败",
        };
      }
    } catch (error) {
      console.error("[TasksHandler] 执行任务异常:", error);
      return {
        success: false,
        error: error.message || "任务执行异常",
      };
    }
  }

  /**
   * 格式化 Claude 输出结果
   * @param {string} output - Claude 输出
   * @param {string} task - 任务描述
   * @param {string} workPath - 工作路径
   * @returns {string} 格式化后的内容
   */
  formatClaudeOutput(output, task, workPath) {
    // 如果输出已经是格式化的 Markdown，直接返回
    if (output && typeof output === "string") {
      return `# 任务执行结果

## 任务描述
${task}

## 工作目录
${workPath}

---

${output}`;
    }

    // 如果是其他格式，转换为字符串
    return `# 任务执行结果

## 任务描述
${task}

## 工作目录
${workPath}

---

${JSON.stringify(output, null, 2)}`;
  }

  /**
   * 处理清空任务
   */
  handleClearTask() {
    console.log("[TasksHandler] 处理清空任务");

    const taskInput = document.getElementById("task-input");
    if (taskInput) {
      taskInput.value = "";
    }

    this.uiUtils.showMessage("任务描述已清空", "info");
  }

  /**
   * 处理复制结果
   */
  async handleCopyResult() {
    console.log("[TasksHandler] 处理复制结果");

    const outputContainer = document.getElementById("task-output");
    if (!outputContainer) return;

    const resultContent = outputContainer.querySelector(".task-result-content");
    if (!resultContent) return;

    const text = resultContent.textContent || resultContent.innerText;

    try {
      await navigator.clipboard.writeText(text);
      this.uiUtils.showMessage("结果已复制到剪贴板", "success");
    } catch (error) {
      console.error("[TasksHandler] 复制失败:", error);
      this.uiUtils.showMessage("复制失败，请手动选择复制", "error");
    }
  }

  /**
   * 处理清空结果
   */
  handleClearResult() {
    console.log("[TasksHandler] 处理清空结果");

    // 清空打字队列
    this.clearTypingQueue();

    const outputContainer = document.getElementById("task-output");
    if (outputContainer) {
      outputContainer.innerHTML = `
                <div class="output-placeholder">
                    <i class="fas fa-brain"></i>
                    <p>准备就绪，请输入任务并点击发送</p>
                </div>
            `;
    }

    this.updateTaskStatus("waiting", "等待任务");
    this.showResultActions(false);

    this.uiUtils.showMessage("结果已清空", "info");
  }

  /**
   * 更新任务状态
   * @param {string} status - 状态类型 (waiting, processing, success, error)
   * @param {string} message - 状态消息
   */
  updateTaskStatus(status, message) {
    const statusElement = document.getElementById("result-status");
    if (!statusElement) return;

    // 移除所有状态类
    statusElement.classList.remove("waiting", "processing", "success", "error");

    // 添加新的状态类
    statusElement.classList.add(status);

    // 更新状态文本
    const statusText = statusElement.querySelector("span");
    if (statusText) {
      statusText.textContent = message;
    }

    console.log("[TasksHandler] 任务状态更新:", { status, message });
  }

  /**
   * 显示/隐藏结果操作按钮
   * @param {boolean} show - 是否显示
   */
  showResultActions(show) {
    const actionsElement = document.getElementById("result-actions");
    if (actionsElement) {
      actionsElement.style.display = show ? "flex" : "none";
    }
  }

  /**
   * 显示执行日志
   * @param {string} task - 任务描述
   * @param {string} workPath - 工作路径
   */
  displayExecutionLog(task, workPath) {
    const outputContainer = document.getElementById("task-output");
    if (!outputContainer) return;

    const timestamp = new Date().toLocaleTimeString("zh-CN");

    outputContainer.innerHTML = `
            <div class="task-execution-log">
                <div class="log-header">
                    <i class="fas fa-terminal"></i>
                    <span>执行日志</span>
                    <span class="log-timestamp">${timestamp}</span>
                </div>
                <div class="log-content">
                    <div class="log-item log-info">
                        <i class="fas fa-info-circle"></i>
                        <span>准备执行任务...</span>
                    </div>
                    <div class="log-item log-info">
                        <i class="fas fa-folder"></i>
                        <span>工作目录: ${workPath}</span>
                    </div>
                    <div class="log-item log-info">
                        <i class="fas fa-tasks"></i>
                        <span>任务: ${task}</span>
                    </div>
                    <div class="log-item log-processing">
                        <i class="fas fa-spinner fa-spin"></i>
                        <span>正在调用 Claude...</span>
                    </div>
                    <div class="log-item log-processing">
                        <i class="fas fa-cog fa-spin"></i>
                        <span>Claude 正在分析和执行任务...</span>
                    </div>
                    <div class="log-item log-wait">
                        <i class="fas fa-clock"></i>
                        <span>请稍候，这可能需要一些时间...</span>
                    </div>
                </div>
            </div>
        `;
  }

  /**
   * 显示任务结果
   * @param {string} content - 结果内容
   */
  displayTaskResult(content) {
    const outputContainer = document.getElementById("task-output");
    if (!outputContainer) return;

    outputContainer.innerHTML = `
            <div class="task-result-content">${this.formatTaskContent(
              content
            )}</div>
        `;
  }

  /**
   * 显示任务错误
   * @param {string} error - 错误信息
   */
  displayTaskError(error) {
    const outputContainer = document.getElementById("task-output");
    if (!outputContainer) return;

    outputContainer.innerHTML = `
            <div class="task-result-content" style="color: #ef4444;">
                <h5>❌ 任务执行失败</h5>
                <p>${error}</p>
            </div>
        `;
  }

  /**
   * 格式化任务内容
   * @param {string} content - 原始内容
   * @returns {string} 格式化后的内容
   */
  formatTaskContent(content) {
    return content
      .replace(/\n/g, "<br>")
      .replace(/```([\s\S]*?)```/g, "<pre><code>$1</code></pre>")
      .replace(/`([^`]+)`/g, "<code>$1</code>")
      .replace(/^# (.*$)/gm, "<h4>$1</h4>")
      .replace(/^## (.*$)/gm, "<h5>$1</h5>")
      .replace(/^### (.*$)/gm, "<h6>$1</h6>")
      .replace(/^\* (.*$)/gm, "<li>$1</li>")
      .replace(/^> (.*$)/gm, "<blockquote>$1</blockquote>");
  }

  /**
   * 处理命令行模式（打开终端并启动 Claude）
   */
  async handleCodeMode() {
    console.log("[TasksHandler] 处理命令行模式 - 打开终端");

    // 检查是否已选择工作路径
    if (!this.currentWorkPath) {
      this.uiUtils.showMessage("请先选择工作路径", "error");
      return;
    }

    // 检查 Claude 是否已连接
    if (!this.claudeConnected) {
      this.uiUtils.showMessage("请等待 Claude 连接成功", "error");
      return;
    }

    try {
      // 检查 electronAPI 是否可用
      if (!window.electronAPI || !window.electronAPI.openTerminalWithClaude) {
        console.error("[TasksHandler] 终端 API 不可用");
        this.uiUtils.showMessage("终端打开功能不可用", "error");
        return;
      }

      // 获取 API Key
      const apiKeyResult = await window.electronAPI.loadApiKey();
      if (!apiKeyResult.success || !apiKeyResult.apiKey) {
        this.uiUtils.showMessage("未配置 API Key，请先在设置页面配置", "error");
        return;
      }

      console.log("[TasksHandler] 打开终端:", this.currentWorkPath);

      // 调用 IPC 打开终端
      const result = await window.electronAPI.openTerminalWithClaude({
        workPath: this.currentWorkPath,
        apiKey: apiKeyResult.apiKey,
      });

      if (result.success) {
        this.uiUtils.showMessage(
          "终端已打开，Claude 命令行模式已启动",
          "success"
        );
      } else {
        this.uiUtils.showMessage(
          `打开终端失败: ${result.error || "未知错误"}`,
          "error"
        );
      }
    } catch (error) {
      console.error("[TasksHandler] 打开终端异常:", error);
      this.uiUtils.showMessage(`打开终端异常: ${error.message}`, "error");
    }
  }

  /**
   * 处理显示对话历史
   */
  handleShowHistory() {
    console.log("[TasksHandler] 处理显示对话历史");

    const sidebar = document.getElementById("history-sidebar");
    const overlay = document.getElementById("sidebar-overlay");

    if (!sidebar || !overlay) return;

    // 显示侧边栏
    sidebar.classList.add("open");
    overlay.classList.add("show");

    // 加载历史记录
    this.loadHistoryRecords();

    console.log("[TasksHandler] 对话历史侧边栏已打开");
  }

  /**
   * 处理关闭对话历史
   */
  handleCloseHistory() {
    console.log("[TasksHandler] 处理关闭对话历史");

    const sidebar = document.getElementById("history-sidebar");
    const overlay = document.getElementById("sidebar-overlay");

    if (!sidebar || !overlay) return;

    // 隐藏侧边栏
    sidebar.classList.remove("open");
    overlay.classList.remove("show");

    console.log("[TasksHandler] 对话历史侧边栏已关闭");
  }

  /**
   * 加载历史记录
   */
  async loadHistoryRecords() {
    console.log("[TasksHandler] 加载历史记录");

    const historyContent = document.getElementById("history-content");
    if (!historyContent) return;

    if (!this.currentWorkPath) {
      historyContent.innerHTML = `
                <div class="history-placeholder">
                    <i class="fas fa-info-circle"></i>
                    <p>请先选择工作路径</p>
                </div>
            `;
      return;
    }

    try {
      // 从存储加载当前工作路径的历史记录
      const result = await window.electronAPI.getWorkspaceHistory({
        workPath: this.currentWorkPath,
        limit: 20,
      });

      if (!result.success || result.tasks.length === 0) {
        historyContent.innerHTML = `
                <div class="history-placeholder">
                    <i class="fas fa-history"></i>
                    <p>暂无对话记录</p>
                </div>
            `;
        return;
      }

      // 渲染历史记录
      const historyHTML = result.tasks
        .map((record, index) => {
          const time = new Date(record.timestamp).toLocaleString("zh-CN", {
            month: "2-digit",
            day: "2-digit",
            hour: "2-digit",
            minute: "2-digit",
          });
          const statusText = record.status === "success" ? "成功" : "失败";

          return `
            <div class="conversation-history-item ${record.status}" onclick="window.tasksHandler.handleSidebarHistoryItemClick('${record.id}')">
                <div class="conversation-history-item-header">
                    <span class="conversation-history-item-time">${time}</span>
                    <span class="conversation-history-item-status ${record.status}">${statusText}</span>
                </div>
                <div class="conversation-history-item-content">${this.escapeHtml(record.task)}</div>
            </div>
        `;
        })
        .join("");

      historyContent.innerHTML = historyHTML;

      console.log("[TasksHandler] 历史记录已加载:", result.tasks.length, "条");
    } catch (error) {
      console.error("[TasksHandler] 加载历史记录失败:", error);
      historyContent.innerHTML = `
                <div class="history-placeholder">
                    <i class="fas fa-exclamation-triangle"></i>
                    <p>加载失败</p>
                </div>
            `;
    }
  }

  /**
   * 转义 HTML 特殊字符
   */
  escapeHtml(text) {
    const div = document.createElement("div");
    div.textContent = text;
    return div.innerHTML;
  }


  /**
   * 处理侧边栏历史记录项点击
   * @param {string} recordId - 记录ID
   */
  async handleSidebarHistoryItemClick(recordId) {
    console.log("[TasksHandler] 处理侧边栏历史记录项点击:", recordId);

    if (!this.currentWorkPath) return;

    try {
      // 获取当前工作路径的历史记录
      const result = await window.electronAPI.getWorkspaceHistory({
        workPath: this.currentWorkPath,
        limit: 20,
      });

      if (!result.success) return;

      // 查找对应的记录
      const record = result.tasks.find((r) => r.id === recordId);

      if (!record) return;

      // 将历史记录内容填入任务输入框
      const taskInput = document.getElementById("task-input");
      if (taskInput) {
        taskInput.value = record.task;
      }

      // 关闭侧边栏
      this.handleCloseHistory();

      this.uiUtils.showMessage("已加载历史任务", "success");
    } catch (error) {
      console.error("[TasksHandler] 加载历史任务失败:", error);
    }
  }

  /**
   * 保存任务到历史记录
   * @param {string} task - 任务内容
   * @param {object} result - 执行结果
   * @param {string} status - 执行状态
   */
  async saveTaskToHistory(task, result, status) {
    if (!this.currentWorkPath) {
      console.warn("[TasksHandler] 未设置工作路径，跳过保存历史");
      return;
    }

    try {
      if (!window.electronAPI || !window.electronAPI.saveWorkspaceTask) {
        console.warn("[TasksHandler] 历史保存API不可用");
        return;
      }

      const taskData = {
        task: task,
        result: status === "success" ? result.content || result.output : null,
        status: status,
        duration: result.duration || null,
        messageCount: result.messageCount || null,
      };

      const saveResult = await window.electronAPI.saveWorkspaceTask({
        workPath: this.currentWorkPath,
        taskData: taskData,
      });

      if (saveResult.success) {
        console.log("[TasksHandler] 任务历史已保存:", saveResult.taskId);

        // 如果侧边栏是打开的，重新加载历史记录
        const sidebar = document.getElementById("history-sidebar");
        if (sidebar && sidebar.classList.contains("open")) {
          this.loadHistoryRecords();
        }
      } else {
        console.error("[TasksHandler] 保存历史失败:", saveResult.message);
      }
    } catch (error) {
      console.error("[TasksHandler] 保存历史异常:", error);
    }
  }

  /**
   * 检测 Claude 连接状态
   */
  async checkClaudeConnection() {
    if (this.checkingConnection) {
      console.log("[TasksHandler] 正在检测连接，跳过");
      return;
    }

    if (!this.currentWorkPath) {
      console.log("[TasksHandler] 未设置工作路径，跳过连接检测");
      this.updateConnectionStatus("disconnected", "未连接", "请先选择工作路径");
      return;
    }

    try {
      this.checkingConnection = true;
      console.log("[TasksHandler] 开始检测 Claude 连接状态");

      // 更新为连接中状态
      this.updateConnectionStatus(
        "connecting",
        "连接中...",
        "正在检测 Claude 可用性..."
      );

      // 检查 electronAPI 是否可用
      if (!window.electronAPI || !window.electronAPI.checkClaudeAvailability) {
        throw new Error("Claude 检测功能不可用");
      }

      // 调用 IPC 检测 Claude
      const result = await window.electronAPI.checkClaudeAvailability(
        this.currentWorkPath
      );
      console.log("[TasksHandler] Claude 检测结果:", result);

      if (result.success && result.available) {
        // 连接成功，启动 Claude 会话
        this.claudeConnected = true;
        const versionInfo = result.version ? ` (${result.version})` : "";

        // 启动持久会话
        await this.startSession();

        const autoApproveInfo = result.message || "Claude 已准备就绪";
        this.updateConnectionStatus(
          "connected",
          "已连接",
          `${autoApproveInfo}${versionInfo}\n工作目录: ${
            result.workPath || this.currentWorkPath
          }`
        );
        this.enableTaskInput();
        this.uiUtils.showMessage("Claude 连接成功！自动批准已启用", "success");
      } else {
        // 连接失败
        this.claudeConnected = false;
        const errorMsg = result.error || "未知错误";
        this.updateConnectionStatus(
          "disconnected",
          "未连接",
          `连接失败: ${errorMsg}`
        );
        this.disableTaskInput();
        this.uiUtils.showMessage(`Claude 连接失败: ${errorMsg}`, "error");
      }
    } catch (error) {
      console.error("[TasksHandler] 检测 Claude 连接异常:", error);
      this.claudeConnected = false;
      this.updateConnectionStatus(
        "error",
        "连接异常",
        `检测失败: ${error.message}`
      );
      this.disableTaskInput();
      this.uiUtils.showMessage(
        `Claude 连接检测异常: ${error.message}`,
        "error"
      );
    } finally {
      this.checkingConnection = false;
    }
  }

  /**
   * 更新连接状态显示
   * @param {string} status - 状态 (disconnected, connecting, connected, error)
   * @param {string} text - 状态文本
   * @param {string} tooltip - 提示信息
   */
  updateConnectionStatus(status, text, tooltip) {
    const statusIndicator = document.getElementById("status-indicator");
    const statusText = document.getElementById("status-text");
    const connectionStatus = document.getElementById(
      "claude-connection-status"
    );

    if (statusIndicator) {
      statusIndicator.setAttribute("data-status", status);
    }

    if (statusText) {
      statusText.textContent = text;
    }

    if (connectionStatus && tooltip) {
      connectionStatus.setAttribute("data-tooltip", tooltip);
    }

    console.log("[TasksHandler] 连接状态已更新:", { status, text, tooltip });
  }

  /**
   * 启用任务输入
   */
  enableTaskInput() {
    const taskInput = document.getElementById("task-input");
    const executeBtn = document.getElementById("execute-task-btn");
    const clearBtn = document.getElementById("clear-task-btn");

    if (taskInput) {
      taskInput.disabled = false;
      taskInput.placeholder =
        "请描述你想要完成的任务，例如：\n帮我写一个 Python 函数来计算斐波那契数列\n或者：\n创建一个简单的网页登录页面";
    }

    if (executeBtn) {
      executeBtn.disabled = false;
    }

    if (clearBtn) {
      clearBtn.disabled = false;
    }

    console.log("[TasksHandler] 任务输入已启用");
  }

  /**
   * 禁用任务输入
   */
  disableTaskInput() {
    const taskInput = document.getElementById("task-input");
    const executeBtn = document.getElementById("execute-task-btn");
    const clearBtn = document.getElementById("clear-task-btn");

    if (taskInput) {
      taskInput.disabled = true;
      taskInput.placeholder = "请先选择工作路径并等待 Claude 连接成功...";
    }

    if (executeBtn) {
      executeBtn.disabled = true;
    }

    if (clearBtn) {
      clearBtn.disabled = true;
    }

    console.log("[TasksHandler] 任务输入已禁用");
  }

  /**
   * 从历史记录加载工作区
   * @param {string} workPath - 工作路径
   */
  async loadWorkspace(workPath) {
    console.log("[TasksHandler] 加载工作区:", workPath);
    
    try {
      // 更新路径输入框
      const pathInput = document.getElementById("work-path-input");
      if (pathInput) {
        pathInput.value = workPath;
      }

      // 启用打开文件位置按钮
      const openLocationBtn = document.getElementById("open-location-btn");
      if (openLocationBtn) {
        openLocationBtn.disabled = false;
      }

      // 保存当前工作路径
      this.currentWorkPath = workPath;

      this.uiUtils.showMessage("工作路径已加载", "success");

      // 检测 Claude 连接状态
      await this.checkClaudeConnection();
      
      // 加载该工作区的对话历史到侧边栏
      await this.loadHistoryRecords();
    } catch (error) {
      console.error("[TasksHandler] 加载工作区失败:", error);
      this.uiUtils.showMessage(`加载工作区失败: ${error.message}`, "error");
    }
  }

  /**
   * 清理事件监听器
   */
  cleanup() {
    // 清理流式事件监听
    console.log("[TasksHandler] 清理流式事件监听");
    this.streamCleanupFunctions.forEach((cleanup) => {
      if (typeof cleanup === "function") {
        cleanup();
      }
    });
    this.streamCleanupFunctions = [];

    // 移除所有事件监听器
    const buttons = [
      "select-path-btn",
      "open-location-btn",
      "execute-task-btn",
      "clear-task-btn",
      "copy-result-btn",
      "clear-result-btn",
      "code-mode-btn",
      "history-btn",
      "close-history-btn",
    ];

    buttons.forEach((buttonId) => {
      const button = document.getElementById(buttonId);
      if (button) {
        button.replaceWith(button.cloneNode(true));
      }
    });

    // 清理路径输入框事件
    const pathInput = document.getElementById("work-path-input");
    if (pathInput) {
      pathInput.replaceWith(pathInput.cloneNode(true));
    }

    // 清理侧边栏遮罩事件
    const sidebarOverlay = document.getElementById("sidebar-overlay");
    if (sidebarOverlay) {
      sidebarOverlay.replaceWith(sidebarOverlay.cloneNode(true));
    }
  }
}

// 导出到全局
window.TasksHandler = TasksHandler;
